<template>
  <div class="table-main">
    <el-dialog
      :close-on-click-modal="false"
      @close="handMyClose"
      :append-to-body="true"
      title="商品"
      :visible.sync="dialogVisible1"
      width="60%"
    >
      <div style="margin-top:50px;" v-loading="loading2">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="商品信息录入" name="first">
            <el-form
              ref="form"
              :model="form"
              label-width="120px"
              :rules="rules"
            >
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商品名称:" prop="goodName">
                    <el-input
                      :disabled="isShow == 3"
                      v-model="form.goodName"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="购买可得经验:" prop="experience">
                    <el-input
                      :disabled="isShow==3"
                      v-model.number="form.experience"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>-->
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="展示价格:" prop="falsePrice">
                    <el-input
                      :disabled="isShow == 3"
                      v-model="form.falsePrice"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="购买可得积分:" prop="integral">
                    <el-input
                      :disabled="isShow == 3"
                      v-model.number="form.integral"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="促销信息:" prop="goodsTips">
                    <el-input
                      type="textarea"
                      :disabled="isShow==3"
                      v-model="form.goodsTips"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>-->
              <el-row :gutter="20" justify="center" type="flex">
                <!-- <el-col :span="8">
                  <el-form-item label="是否推荐:" prop="isRecom">
                    <el-radio-group v-model="form.isRecom" :disabled="isShow==3">
                      <el-radio :label="1" :disabled="isShow==3">是</el-radio>
                      <el-radio :label="2" :disabled="isShow==3">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>-->
                <el-col :span="8">
                  <el-form-item label="是否热销:" prop="isHot">
                    <el-radio-group
                      v-model="form.isHot"
                      :disabled="isShow == 3"
                    >
                      <el-radio :label="1" :disabled="isShow == 3">是</el-radio>
                      <el-radio :label="2" :disabled="isShow == 3">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否新品:" prop="isNew">
                    <el-radio-group
                      v-model="form.isNew"
                      :disabled="isShow == 3"
                    >
                      <el-radio :label="1" :disabled="isShow == 3">是</el-radio>
                      <el-radio :label="2" :disabled="isShow == 3">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <!-- <el-col :span="8">
                  <el-form-item label="是否精品:" prop="isBest">
                    <el-radio-group v-model="form.isBest" :disabled="isShow==3">
                      <el-radio :label="1" :disabled="isShow==3">是</el-radio>
                      <el-radio :label="2" :disabled="isShow==3">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>-->
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <!-- <el-col :span="16">
                  <el-form-item label="是否上架:" prop="isPut">
                    <el-radio-group v-model="form.isPut" :disabled="isShow==3">
                      <el-radio :label="1" :disabled="isShow==3">是</el-radio>
                      <el-radio :label="2" :disabled="isShow==3">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>-->
              </el-row>

              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商品类目:" prop="goodTypeId">
                    <el-cascader
                      @change="handData"
                      ref="myCascader"
                      :props="defaultParams"
                      :options="goodClassList"
                      :disabled="isShow == 3"
                      v-model="form.goodTypeId"
                    ></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商品单位:" prop="goodUnit">
                    <el-select
                      filterable
                      :disabled="isShow == 3"
                      v-model="form.goodUnit"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in companyList"
                        :key="item.id"
                        :label="item.dataValue"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                    <el-button
                      type="primary"
                      v-if="isShow != 3"
                      icon="el-icon-plus"
                      @click="handAddGoodUnit"
                      >添加</el-button
                    >
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商品品牌:" prop="brand">
                    <el-select
                      filterable
                      :disabled="isShow == 3"
                      v-model="form.brand"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in brandList"
                        :key="item.id"
                        :label="item.dataValue"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                    <el-button
                      type="primary"
                      v-if="isShow != 3"
                      icon="el-icon-plus"
                      @click="handAddBrand"
                      >添加</el-button
                    >
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="是否包邮:" prop="isFreeShipping">
                    <el-select
                      filterable
                      :disabled="isShow == 3"
                      v-model="form.isFreeShipping"
                      placeholder="请选择"
                    >
                      <el-option label="是" :value="1"></el-option>
                      <el-option label="否" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商品类型:" prop="goodsFlag">
                    <el-select
                      filterable
                      :disabled="isShow == 3"
                      v-model="form.goodsFlag"
                      placeholder="请选择"
                    >
                      <el-option label="虚拟商品" :value="2"></el-option>
                      <el-option label="实物商品" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商家店铺:" prop="shops">
                    <el-select
                      filterable
                      :disabled="isShow == 3"
                      v-model="form.shops"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in findAllsList"
                        :key="item.id"
                        :label="item.shopName"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商品主图:" prop="mainImg">
                    <el-upload
                      :headers="headers"
                      accept=".jpg,.png,.gif.svg,.bmp,.jpeg"
                      v-if="isShow != 3"
                      class="avatar-uploader"
                      :action="
                        $store.state.app.newUrl + '/admin/wxUser/uoloadfile'
                      "
                      :show-file-list="false"
                      :on-success="handSuccess"
                      :before-upload="beforeAvatarUpload"
                      v-loading="loadingUploda"
                    >
                      <img
                        v-if="form.mainImg != '' && form.mainImg != undefined"
                        :src="form.mainImg"
                        class="avatar"
                      />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      <div slot="tip" class="el-upload__tip">
                        只能上传378*378大小的图片
                      </div>
                    </el-upload>
                    <img
                      v-if="isShow == 3"
                      :src="form.mainImg"
                      class="avatar"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-form-item label="商品轮播:" prop="resourcesList">
                    <el-upload
                      :on-change="onChange"
                      :headers="headers"
                      accept=".jpg,.png,.gif.svg,.bmp,.jpeg"
                      v-if="isShow != 3"
                      class="avatar-uploader"
                      :action="
                        $store.state.app.newUrl + '/admin/wxUser/uoloadfile'
                      "
                      :on-success="handSuccess2"
                      :before-upload="beforeAvatarUpload2"
                      list-type="picture-card"
                      v-loading="loadingUploda2"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :file-list="form.resourcesList"
                      multiple
                    >
                      <i class="el-icon-plus"></i>
                      <div slot="tip" class="el-upload__tip">
                        只能上传750*750大小的图片
                      </div>
                    </el-upload>
                    <div v-if="isShow == 3" class="img_item_box">
                      <img
                        v-for="imgItem in form.resourcesList"
                        :key="imgItem.id"
                        :src="imgItem.resPath"
                        class="avatar"
                      />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品详情录入" name="second">
            <myTinymce ref="ceshifuwenben"></myTinymce>
          </el-tab-pane>
        </el-tabs>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handFromSub('form')"
          v-if="isShow != 3"
          :loading="bntLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { imgSizi } from "@/utils/myUtils";
import myTinymce from "@/components/Tinymce";
export default {
  name: "SidebarLogo",
  components: {
    myTinymce
  },
  watch: {
    isState(newObj) {
      this.isShow = newObj;
    }
  },
  props: {
    isState: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loadingUploda2: false,
      bntLoading: false,
      headers: {
        token: localStorage.getItem("mytoken") || ""
      },
      rules: {
        goodName: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        // resourcesList: [
        //   { required: true, message: '请上传图片', trigger: 'blur' }
        // ],
        mainImg: [{ required: true, message: "请上传图片", trigger: "blur" }],
        experience: [
          { required: true, message: "请输入购买可得经验", trigger: "blur" },
          { type: "number", message: "经验必须为数字值", trigger: "blur" }
        ],
        falsePrice: [
          { required: true, message: "请输入展示价格", trigger: "blur" },
          {
            validator(rule, value, callback) {
              var reg = /^[0-9]{1}([0-9]|[.])*$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入展示价格"));
              }
            },
            trigger: "blur"
          }
        ],
        integral: [
          { required: true, message: "请输入购买可得积分", trigger: "blur" },
          { type: "number", message: "积分必须为数字值", trigger: "blur" }
        ],
        goodsTips: [
          { required: true, message: "请输入促销信息", trigger: "blur" }
        ],
        isRecom: [
          { required: true, message: "请选择是否推荐", trigger: "blur" }
        ],
        isNew: [
          {
            required: true,
            message: "请选择是否新品",
            trigger: "blur"
          }
        ],
        isBest: [
          {
            required: true,
            message: "请选择是否精品",
            trigger: "blur"
          }
        ],
        isHot: [{ required: true, message: "请选择是否热销", trigger: "blur" }],
        isPut: [{ required: true, message: "请选择是否上架", trigger: "blur" }],
        goodTypeId: [
          {
            required: true,
            message: "请选择商品类目",
            trigger: "change"
          }
        ],
        // brand: [
        //   { required: true, message: '请选择商品品牌', trigger: 'change' }
        // ],
        isFreeShipping: [
          { required: true, message: "请选择是否包邮", trigger: "change" }
        ],
        goodsFlag: [
          { required: true, message: "请选择商品类型", trigger: "change" }
        ],
        shops: [
          { required: true, message: "请选择商家店铺", trigger: "change" }
        ],
        goodUnit: [
          { required: true, message: "请选择商品单位", trigger: "change" }
        ]
      },
      loadingUploda: false,
      defaultParams: {
        label: "title",
        value: "id",
        children: "children"
      },
      form: { goodTypeId: "" },
      shopStatusOptions: [],
      isShow: 0,
      imageUrl: "",
      dialogImageUrl: "",
      dialogVisible1: false,
      addressKeyword: "",
      activeName: "first",
      dialogVisible: false,
      brandList: [],
      goodClassList: [],
      findAllsList: [],
      loading2: true,
      companyList: []
    };
  },
  async mounted() {
    // this.$api.getGoodsListl().then(res => {
    //   this.shopStatusOptions = res.data.data
    // })

    this.companyList = (await this.$api.getFindCompany()).data.data;
    console.log(this.companyList, "单位");
  },
  methods: {
    handAddGoodUnit() {
      this.$prompt("请输入单位名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: "请输入单位名称"
      })
        .then(({ value }) => {
          let form = {
            dataValue: value,
            dataType: "Company",
            pid: this.companyList[0].pid || ""
          };
          this.$api
            .addSysDict(form)
            .then(async res => {
              this.form.goodUnit = res.data.data;
              this.companyList = (await this.$api.getFindCompany()).data.data;
              this.$message({
                message: res.data.message,
                type: "success"
              });
            })
            .finally(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    handAddBrand() {
      this.$prompt("请输入品牌名字", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        inputErrorMessage: "请输入品牌名称"
      })
        .then(({ value }) => {
          let form = {
            dataValue: value,
            dataType: "Brand",
            pid: this.brandList[0].pid || ""
          };
          this.$api
            .addSysDict(form)
            .then(async res => {
              this.form.brand = res.data.data;
              this.brandList = (await this.$api.getSysBrand()).data.data;
              this.$message({
                message: res.data.message,
                type: "success"
              });
            })
            .finally(() => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    handData(val) {
      console.log(this.form.goodTypeId, val);
    },
    async handGetList(val, id) {
      this.activeName = "first";
      this.loading2 = false;
      this.brandList = (await this.$api.getSysBrand()).data.data;

      this.$refs.ceshifuwenben.init2();
      this.findAllsList = (await this.$api.userByShop()).data.data;
      console.log("商家当店铺", this.findAllsList);
      let newData = (await this.$api.getGoodsTypeTreeinfo()).data.data;
      if (id) {
        this.form.shops = id;
      }

      newData.forEach(item => {
        if (item.children.length == 0) {
          item.disabled = true;
        }
      });
      this.goodClassList = this.getTreeData(newData);
      if (val == 1) {
        this.$refs.ceshifuwenben.setContent("");
      }
    },
    handGetShop(id) {
      this.$forceUpdate();
      this.loading2 = true;
      this.$api.getSysSelectGoodsByIdGoods(id).then(async res => {
        console.log("详情吗", res.data.data);
        res.data.data.shops = parseInt(res.data.data.shops);
        res.data.data.resourcesList.forEach(item => {
          item.url = item.resPath;
        });
        await this.$refs.ceshifuwenben.init();
        this.$refs.ceshifuwenben.setContent(res.data.data.details);
        this.form = res.data.data;
        this.form.goodTypeId = this.form.goodTypeId + "";
        this.loading2 = false;
      });
    },
    onChange() {
      this.loadingUploda2 = false;
    },
    handSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log(res, "==");
      this.loadingUploda = false;
      var url = JSON.parse(res.message);
      this.$set(this.form, "mainImg", url.url);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isJPG = file.type === "image/jpeg";
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      const isSize = imgSizi(file, 378, 378);
      console.log(isLt2M && isSize, "sss");
      return isSize;
    },
    handMyClose() {
      this.$refs.ceshifuwenben.Myremove();
      // this.$refs.form.resetFields()
      for (let key in this.form) {
        this.form[key] = "";
      }
      this.$refs.ceshifuwenben.fwbObj = "";
      this.form.resourcesList = [];
    },
    handFromSub(formName) {
      this.$refs.ceshifuwenben.getContent();
      this.form.shopStatus = 1;
      this.form.details = this.$refs.ceshifuwenben.fwbObj;
      this.form.goodAttributeList = null;
      this.form.resourcesList.forEach(item => {
        if (item.response) {
          let newImg = JSON.parse(item.response.message);
          item.resPath = newImg.url;
          item.imagePurpose = 1;
          item.isDelete = 2;
          item.resType = 1;
        }
      });
      //1编辑
      if (this.isState == 1) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.bntLoading = true;

            if (typeof this.form.goodTypeId == "string") {
            } else {
              this.form.goodTypeId = this.form.goodTypeId[
                this.form.goodTypeId.length - 1
              ];
            }
            console.log("编辑", this.form);
            let shop = this.form;

            if (!this.$refs.ceshifuwenben.fwbObj) {
              this.$message({
                message: "请录入商品详情"
              });
              this.activeName = "second";
              console.log(
                this.$refs.ceshifuwenben.fwbObj,
                "this.$refs.ceshifuwenben.fwbObj"
              );
              return;
            }
            if (this.form.resourcesList.length != 0) {
              this.form.resourcesList.forEach(item => {
                delete item.url;
                item.fromType = 2;
              });
            }

            this.$api
              .getSysEditGoods(this.form)
              .then(res => {
                this.dialogVisible1 = false;
                this.bntLoading = true;
                this.$parent.init();

                this.$refs.ceshifuwenben.init();
                this.$message({
                  message: res.data.message,
                  type: "success"
                });
              })
              .finally(() => {
                this.bntLoading = false;
              });
          } else {
            console.log("error submit!!");
            this.$message({
              message: "请完成表单录入"
            });
            this.activeName = "first";
            this.bntLoading = false;
            return false;
          }
        });
      } else if (this.isState == 0) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            if (!this.$refs.ceshifuwenben.fwbObj) {
              this.$message({
                message: "请录入商品详情"
              });
              this.activeName = "second";
              console.log(
                this.$refs.ceshifuwenben.fwbObj,
                "this.$refs.ceshifuwenben.fwbObj"
              );
              return;
            }
            this.bntLoading = true;
            // this.form.goodTypeId = this.form.goodTypeId[0]
            if (typeof this.form.goodTypeId == "string") {
            } else {
              this.form.goodTypeId = this.form.goodTypeId[
                this.form.goodTypeId.length - 1
              ];
            }
            this.form.resourcesList.forEach(item => {
              item.fromType = 2;
            });
            let shop = this.form;
            this.$api
              .getSysAddGoods(this.form)
              .then(res => {
                console.log(res, "添加商品", this.form);
                this.bntLoading = false;
                this.dialogVisible1 = false;
                this.$parent.init();
                this.$refs.form.resetFields();
                this.$refs.ceshifuwenben.init();
                this.$message({
                  message: res.data.message,
                  type: "success"
                });
              })
              .finally(() => {
                this.bntLoading = false;
              });
          } else {
            console.log("error submit!!");
            this.$message({
              message: "请完成表单录入"
            });
            this.activeName = "first";
            return false;
          }
        });
      }
    },

    // handSuccess(response, file, fileList) {
    //   console.log(response, file, fileList, '成功回调')
    //   this.form.shopImg = response.message
    // },
    handSuccess2(res, file, fileList) {
      this.loadingUploda2 = false;
      this.form.resourcesList = fileList;
    },
    beforeAvatarUpload2(file) {
      this.loadingUploda2 = true;
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isJPG = file.type === "image/jpeg";
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      const isSize = imgSizi(file, 750, 750);
      isSize
        .then(res => {})
        .catch(err => {
          this.loadingUploda2 = false;
        });
      return isSize;
    },
    handleRemove(file, fileList) {
      // console.log(fileList, "?????????", file, this.form.resourcesList);
      // if (fileList.length == 0) {
      //   this.form.resourcesList = [];
      //   return;
      // }
      // if (fileList[0].response == undefined) {
      //   this.form.resourcesList = fileList;
      // } else {
      //   this.form.resourcesList = [];
      //   fileList.forEach(item => [
      //     this.form.resourcesList.push({
      //       resPath: JSON.parse(file.response.message).url,
      //       url: JSON.parse(file.response.message).url,
      //       imagePurpose: 1,
      //       isDelete: 2,
      //       resType: 1
      //     })
      //   ]);
      // }
      // console.log(this.form.resourcesList, "chengg");
      this.form.resourcesList = fileList;
    },
    handlePictureCardPreview(file, fileList) {
      console.log(file, fileList);
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handMapShow() {
      this.dialogVisible = true;
    },
    handleClick() {},
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined;
        } else {
          this.getTreeData(data[i].children);
        }
      }

      return data;
    }
  }
};
</script>

<style lang="scss" scoped>
.img_item_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  img {
    margin-right: 8px;
    margin-bottom: 8px;
    border-radius: 6px;
  }
}
.map_btn {
  width: 82px;
  height: 22px;
  background: rgba(56, 173, 147, 1);
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  line-height: 22px;
  text-align: center;
  margin-top: 8px;
}
/deep/ .el-form-item__label {
  font-size: 14px;
  color: #000;
  font-weight: bold;
}
.form_box {
  width: 80%;
  margin: 0 auto;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #38ad93;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #38ad93;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
